# -*- coding: utf-8 -*-

import json


json_str = {"nodes":{}, "edges":{}}

try:
    f1 = open("../json/graph.dot", "r")
    f2 = open("../json/vad0.json", "w")
    with open("../json/vadinfo0.json", 'r') as load_f:
        vadinfo = json.load(load_f)
    # transform .dot file to .json
    pid_flag = False
    for line in f1:
        if "Pid" in line:
            pid_flag = True
            root = True
            pid = line[7:14].strip()
            json_str["nodes"][pid] = {}
            json_str["edges"][pid] = []
            continue
        if pid_flag:
            if "->" in line:
                if root:
                    vad = line[:12]
                    start_address = vadinfo[pid][0]["start"]
                    end_address = vadinfo[pid][0]["end"]
                    address = hex(start_address)[2:] + " - " + hex(end_address)[2:]
                    json_str["nodes"][pid][vad] = {"color":"blue", "address":address}
                    root = False
                tmp = {"source":line[0:12], "target":line[16:28]}
                json_str["edges"][pid].append(tmp)
            if "label" in line:
                vad = line[:12]
                address = line[31:50]
                color = line[115:-4]
                if color == "red":
                    color = "purple"
                json_str["nodes"][pid][vad] = {"color": color, "address":address}
            if "/*" in line:
                pid_flag = False
                continue

    # dealing with vadinfo.json file which store details of every node    
    for pid in vadinfo.keys():
        for node in vadinfo[pid]:
            k = "vad_"+hex(node["vad"])[2:]
            json_str["nodes"][pid][k].update(node)

    f2.write(json.dumps(json_str))

finally:
    if f1:
        f1.close()
    if f2:
        f2.close()